#include "Input.h"
#include "GameMain.h";


Input::Input(Ogre::RenderWindow* Window, GameMain* gm)
{
	mGm = gm;
	mWindow = Window;
	Ogre::LogManager::getSingletonPtr()->logMessage("*** Initializing OIS ***");
	OIS::ParamList pl;
	size_t windowHnd = 0;
	std::ostringstream windowHndStr;
 
	mWindow->getCustomAttribute("WINDOW", &windowHnd);
	windowHndStr << windowHnd;
	pl.insert(std::make_pair(std::string("WINDOW"), windowHndStr.str()));
 
	mInputManager = OIS::InputManager::createInputSystem(pl);

	mKeyboard = static_cast<OIS::Keyboard*>(mInputManager->createInputObject( OIS::OISKeyboard, true ));
	mMouse = static_cast<OIS::Mouse*>(mInputManager->createInputObject( OIS::OISMouse, true ));

	mMouse->setEventCallback(this);
	mKeyboard->setEventCallback(this);

	//Set initial mouse clipping size
	windowResized(mWindow);	
}

//Adjust mouse clipping area
void Input::windowResized(Ogre::RenderWindow* rw)
{
    unsigned int width, height, depth;
    int left, top;
    rw->getMetrics(width, height, depth, left, top);
 
    const OIS::MouseState &ms = mMouse->getMouseState();
    ms.width = width;
    ms.height = height;
}
 
//Unattach OIS before window shutdown (very important under Linux)
void Input::windowClosed(Ogre::RenderWindow* rw)
{
    //Only close for window that created OIS (the main window in these demos)
    if(rw == mWindow)
    {
        if(mInputManager)
        {
            mInputManager->destroyInputObject( mMouse );
            mInputManager->destroyInputObject( mKeyboard );
 
            OIS::InputManager::destroyInputSystem(mInputManager);
            mInputManager = 0;
        }
    }
}

bool Input::capture(void) {
	mMouse->capture();
	mKeyboard->capture();
	if(mKeyboard->isKeyDown(OIS::KC_ESCAPE))
        return false;
	return true;
}

Input::~Input(void)
{
	windowClosed(mWindow);
}

bool Input::keyPressed(const OIS::KeyEvent& evt) {
	mGm->KeyPressed(evt);   
    return true;
}
bool Input::keyReleased( const OIS::KeyEvent& evt ){
	mGm->KeyReleased(evt);   
    return true;
}
// OIS::MouseListener
bool Input::mouseMoved( const OIS::MouseEvent& evt ){
    mGm->MouseMoved(evt);
	return true;

}
bool Input::mousePressed( const OIS::MouseEvent& evt, OIS::MouseButtonID id ){
	mGm->MousePressed(evt, id);
	return true;
}
bool Input::mouseReleased( const OIS::MouseEvent& evt, OIS::MouseButtonID id ){
	mGm->MouseReleased(evt, id);
	return true;
}